//
//  DiscoveryDetailViewController.swift
//  clreader
//
//  Created by colin on 2019/3/6.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class DiscoveryDetailViewController: CLBaseViewController {

    private var goodsId = 0
    
    private lazy var topBar = CLNavigationBar()
    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var infoData = [JSONObject]()
    
    convenience init(goodsId:Int) {
        self.init()
        self.goodsId = goodsId
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //topBar
        self.topBar.do {
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        }
        self.topBar.show(inView: self.view)
        
        self.view.addSubview(self.infoTableView)
        self.infoTableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.topBar.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        self.infoTableView.do {
            $0.backgroundColor = UIColor(hex: "f2f3f5")
            $0.separatorStyle = .none
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.register(BookCell.self, forCellReuseIdentifier: BookCell.reuseId)
            $0.dataSource = self
            $0.delegate = self
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
            $0.mj_header?.beginRefreshing()
        }
    }

}

extension DiscoveryDetailViewController {
    
    private func refresh() {
        _ = Router.goods_subjectinfo(goods_id: self.goodsId).request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.infoTableView.mj_header.endRefreshing()
            
            if case .success(let successData,_) = response {
                if let subject = successData?["subject"] as? JSONObject,
                    let title = subject["title"] as? String {
                    self?.topBar.title = title
                }
                
                if let subjectInfo = successData?["subjectInfo"] as? [JSONObject] {
                    self?.infoData = subjectInfo
                } else {
                    self?.infoData = []
                }
                
                self?.infoTableView.reloadData()
            }
            
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
    }
}

extension DiscoveryDetailViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.infoData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: BookCell.reuseId) as! BookCell
        cell.refresh(data: self.infoData[indexPath.row])
        return cell
    }
}

extension DiscoveryDetailViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return BookCell.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let sourceType = SourceType(type: self.infoData[indexPath.row]["type"] as? Int),
            let goods_id = self.infoData[indexPath.row]["goods_id"] as? Int, goods_id > 0 {
            if sourceType == .电子书 {
                let controller = EBookDetailViewController(goods_id: goods_id)
                self.show(controller, sender: nil)
            } else {
                let controller = SourceDetailViewController(sourceType: sourceType, goods_id: goods_id)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            }
            
        }
    }
}
